package com.cloudinnov.websocket;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudinnov.logic.RealTimeDataLogic;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.support.spring.SpringUtils;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Description: <br/>
 * Copyright (c),2011-2017 <br/>
 * This program is protected by copyright Cloudinnov; <br/>
 * Program Name: <br/>
 * Dte:
 * @author chengning
 * @date 2017年4月6日下午4:08:04
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@ServerEndpoint("/equipmentState/{sectionCode}")
public class EquipmentStateWebsocket {
	private static Logger LOG = LoggerFactory.getLogger(EquipmentStateWebsocket.class);
	public static final String SPLIT1 = ":";
	private String random;
	private static int onlineCount = 0;
	// 用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
	public static ConcurrentMap<String, EquipmentStateWebsocket> webSocketMap = new ConcurrentHashMap<String, EquipmentStateWebsocket>();
	// 用来发送数据
	private Session session;
	private RealTimeDataLogic realTimeDataLogic = SpringUtils.getBean("realTimeDataLogic");

	@OnOpen
	public void onOpen(@PathParam("sectionCode") String sectionCode, Session session) {
		this.session = session;
		this.random = CommonUtils.getUUID();
		webSocketMap.put(sectionCode + SPLIT1 + random, this);
		// 连接人数加1
		addOnlineCount();
		List<Equipments> data = realTimeDataLogic.selectRealtimeIndexTypeDataBySectionCode(sectionCode);
		try {
			
			ObjectMapper mapper = new ObjectMapper();
			mapper.setSerializationInclusion(Include.NON_NULL);
			this.sendMessage(mapper.writeValueAsString(data));
			
		} catch (IOException e) {
			LOG.error("EquipmentStateWebsocket is error, data : {}, error: {}", data, e);
		}
		LOG.debug("设备状态推送开始连接:" + random);
	}
	
	@OnMessage
	public void onMessage(@PathParam("sectionCode") String sectionCode, String message) {
	}
	
	@OnError
	public void onError(Throwable throwable, Session session) throws IOException {
		session.close();
		LOG.error("设备状态推送异常:" + random);
	}
	
	@OnClose
	public void onClose(Session session) throws IOException {
		webSocketMap.remove(random);
		subOnlineCount(); // 在线数减1
		session.close();
		LOG.debug("设备状态推送连接关闭:" + random);
	}
	
	public synchronized void sendMessage(String message) throws IOException {
		if (this.session.isOpen()) {
			this.session.getBasicRemote().sendText(message);
		}
	}
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	public static synchronized void addOnlineCount() {
		EquipmentStateWebsocket.onlineCount++;
	}
	public static synchronized void subOnlineCount() {
		EquipmentStateWebsocket.onlineCount--;
	}
}
